<?php

namespace App\Http\Controllers;

use App\Handlers\ImageUploadHandler;
use App\Handlers\SlugTranslateHandler;
use App\Jobs\TranslateSlug;
use App\Models\Category;
use App\Models\Link;
use App\Models\Topic;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\TopicRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

class TopicsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth', ['except' => ['index', 'show']]);
    }

    public function index(Request $request, Topic $topic, User $user, Link $link)
    {
        $topics = $topic->withOrder($request->order)
            ->with(['category', 'user'])
            // ->whereHas('user', function ($q) { // todo 如果 topics 有数据，而 users 表没有数据 或者 categories 表没有数据，怎么查询?
            //     return $q->exists();
            // })
            ->paginate();

        $active_users = $user->getActiveUsers();
        $links = $link->getAllCached();

        return view('topics.index', compact('topics', 'active_users', 'links'));
    }

    public function show(Request $request, Topic $topic)
    {
        // URL 矫正
        // if ( ! empty($topic->slug) && $topic->slug != $request->slug) {
        //     return redirect($topic->link(), 301);
        // }
        // 文章访问量统计，同一个ip地址5分钟内只记录一次
        $uvKey = "topic:view:id" . $topic->id . ":ip" . $request->ip();
        if(!Cache::get($uvKey)) {
            Cache::add($uvKey, 1, 10);
            $topic->increment('view_count');
            $topic->save();
        }
        return view('topics.show', compact('topic'));
    }

    public function create(Topic $topic)
    {
        $categories = Category::all();
        return view('topics.create_and_edit', compact('topic', 'categories'));
    }

    public function store(TopicRequest $request, Topic $topic)
    {
        $topic->fill($request->all());
        $topic->body = clean($topic->body, 'user_topic_body');
        $topic->user_id = Auth::id();
        // todo 是否需要观察者来更新 帖子的简介 字段的值
        $topic->excerpt = make_excerpt($topic->body);

        // $topic->slug = app(SlugTranslateHandler::class)->translate($topic->title);
        // 异步队列处理 翻译
        $topic->save();

        if (true && !$topic->slug) {
            // 推送任务到队列，需要开启队列监听 php artisan queue:listen
            dispatch(new TranslateSlug($topic));
        }

        return redirect()->to($topic->link())->with('success', '帖子创建成功~');
    }

    public function edit(Topic $topic)
    {
        $this->authorize('update', $topic);
        $categories = Category::all();
        return view('topics.create_and_edit', compact('topic', 'categories'));
    }

    public function update(TopicRequest $request, Topic $topic)
    {
        $this->authorize('update', $topic);
        $data = $request->all();
        $data['body'] = clean($data['body'], 'user_topic_body');
        $data['excerpt'] = make_excerpt($data['body']);
        $data['slug'] = app(SlugTranslateHandler::class)->translate($data['title']);
        $topic->update($data);

        return redirect()->to($topic->link())->with('success', '更新成功~');
    }

    public function destroy(Topic $topic)
    {
        $this->authorize('destroy', $topic);
        $topic->delete();

        // todo 删除文章 - 评论也要删除
        return redirect()->route('topics.index')->with('success', '成功删除~！');
    }

    public function uploadImage(Request $request, ImageUploadHandler $uploadHandler)
    {
        $data = [
            'success'   => false,
            'msg'       => '上传失败',
            'file_path' => ''
        ];

        // 判断是否有上传文件，并赋值给 $file
        if ($file = $request->upload_file) {
            // 保存图片到本地
            $result = $uploadHandler->save($file, 'topics', Auth::id(), 1024);
            if ($result) {
                $data['file_path'] = $result['path'];
                $data['msg'] = '上传成功';
                $data['success'] = true;
            }
        }
        return $data;
    }
}
